<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能Agent代理系统测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f172a 100%);
            color: white;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 2.5rem;
            color: #00f5ff;
            margin-bottom: 10px;
            text-shadow: 0 0 20px rgba(0, 245, 255, 0.5);
        }

        .header p {
            color: #94a3b8;
            font-size: 1.1rem;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }

        .card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(0, 245, 255, 0.3);
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }

        .card h3 {
            color: #00f5ff;
            margin-bottom: 16px;
            font-size: 1.25rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
        }

        .status-online { background: #10b981; animation: pulse 2s infinite; }
        .status-offline { background: #ef4444; }
        .status-warning { background: #f59e0b; animation: pulse 2s infinite; }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .button {
            background: linear-gradient(135deg, #00f5ff, #0ea5e9);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 5px;
        }

        .button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 245, 255, 0.3);
        }

        .button.danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }

        .button.warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
        }

        .button.success {
            background: linear-gradient(135deg, #10b981, #059669);
        }

        .log-container {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 8px;
            padding: 16px;
            height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
            margin-top: 16px;
        }

        .log-entry {
            margin-bottom: 8px;
            padding: 4px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .log-timestamp {
            color: #64748b;
            margin-right: 8px;
        }

        .log-info { color: #00f5ff; }
        .log-success { color: #10b981; }
        .log-warning { color: #f59e0b; }
        .log-error { color: #ef4444; }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-top: 16px;
        }

        .stat-item {
            background: rgba(255, 255, 255, 0.05);
            padding: 16px;
            border-radius: 8px;
            text-align: center;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #00f5ff;
            margin-bottom: 4px;
        }

        .stat-label {
            color: #94a3b8;
            font-size: 0.875rem;
        }

        .notification-demo {
            position: fixed;
            top: 20px;
            right: 20px;
            max-width: 400px;
            background: rgba(0, 0, 0, 0.9);
            border: 1px solid #00f5ff;
            border-radius: 8px;
            padding: 16px;
            backdrop-filter: blur(10px);
            transform: translateX(500px);
            transition: transform 0.3s ease;
            z-index: 1000;
        }

        .notification-demo.show {
            transform: translateX(0);
        }

        .test-results {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            padding: 16px;
            margin-top: 16px;
        }

        .test-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .test-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: bold;
        }

        .test-pass { background: #10b981; color: white; }
        .test-fail { background: #ef4444; color: white; }
        .test-pending { background: #f59e0b; color: white; }

        .digital-human-demo {
            text-align: center;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            margin-top: 16px;
        }

        .avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #00f5ff, #0ea5e9);
            margin: 0 auto 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            position: relative;
            overflow: hidden;
        }

        .avatar.speaking {
            animation: speaking-animation 1s infinite;
            box-shadow: 0 0 30px rgba(0, 245, 255, 0.6);
        }

        @keyframes speaking-animation {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .message-bubble {
            background: rgba(0, 245, 255, 0.2);
            border: 1px solid rgba(0, 245, 255, 0.5);
            border-radius: 16px;
            padding: 16px;
            margin-top: 16px;
            position: relative;
            min-height: 60px;
            display: flex;
            align-items: center;
        }

        .message-bubble::before {
            content: '';
            position: absolute;
            top: -8px;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 8px solid transparent;
            border-right: 8px solid transparent;
            border-bottom: 8px solid rgba(0, 245, 255, 0.5);
        }

        .typewriter-text {
            font-size: 1rem;
            color: #e2e8f0;
        }

        .cursor {
            display: inline-block;
            background: #00f5ff;
            width: 2px;
            height: 20px;
            animation: blink 1s infinite;
        }

        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0; }
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            overflow: hidden;
            margin-top: 8px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #00f5ff, #0ea5e9);
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 智能Agent代理系统测试</h1>
            <p>税务大模型多智能协同体项目 - 智能推送与数字人播报系统验证</p>
        </div>

        <div class="grid">
            <!-- 系统状态监控 -->
            <div class="card">
                <h3>
                    <span class="status-indicator" id="systemStatus"></span>
                    系统状态监控
                </h3>
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-value" id="totalPushes">0</div>
                        <div class="stat-label">总推送数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="highPriorityPushes">0</div>
                        <div class="stat-label">高优先级</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="announcements">0</div>
                        <div class="stat-label">播报次数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="policyMatches">0</div>
                        <div class="stat-label">政策匹配</div>
                    </div>
                </div>
                <div style="margin-top: 16px;">
                    <button class="button success" onclick="startAgent()">启动代理</button>
                    <button class="button danger" onclick="stopAgent()">停止代理</button>
                    <button class="button" onclick="resetStats()">重置统计</button>
                </div>
            </div>

            <!-- 核心功能测试 -->
            <div class="card">
                <h3>🔧 核心功能测试</h3>
                <div class="test-results" id="testResults">
                    <div class="test-item">
                        <span>智能代理初始化</span>
                        <span class="test-status test-pending" id="test-init">待测试</span>
                    </div>
                    <div class="test-item">
                        <span>政策推荐生成</span>
                        <span class="test-status test-pending" id="test-recommendations">待测试</span>
                    </div>
                    <div class="test-item">
                        <span>通知推送系统</span>
                        <span class="test-status test-pending" id="test-notifications">待测试</span>
                    </div>
                    <div class="test-item">
                        <span>数字人播报</span>
                        <span class="test-status test-pending" id="test-broadcast">待测试</span>
                    </div>
                    <div class="test-item">
                        <span>用户画像分析</span>
                        <span class="test-status test-pending" id="test-profile">待测试</span>
                    </div>
                </div>
                <div style="margin-top: 16px;">
                    <button class="button" onclick="runAllTests()">运行全部测试</button>
                    <button class="button warning" onclick="testPolicyRecommendations()">测试政策推荐</button>
                    <button class="button warning" onclick="testNotificationPush()">测试通知推送</button>
                </div>
            </div>

            <!-- 数字人播报演示 -->
            <div class="card">
                <h3>🎙️ AI数字人播报演示</h3>
                <div class="digital-human-demo">
                    <div class="avatar" id="digitalAvatar">🤖</div>
                    <div class="message-bubble">
                        <div class="typewriter-text" id="broadcastMessage">欢迎使用智能Agent代理系统！我是您的AI数字人助手。</div>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" id="broadcastProgress" style="width: 0%;"></div>
                    </div>
                </div>
                <div style="margin-top: 16px;">
                    <button class="button" onclick="triggerManualBroadcast()">手动播报</button>
                    <button class="button warning" onclick="triggerUrgentBroadcast()">紧急播报</button>
                    <button class="button success" onclick="triggerPolicyBroadcast()">政策播报</button>
                    <button class="button" onclick="stopBroadcast()">停止播报</button>
                </div>
            </div>

            <!-- 性能压力测试 -->
            <div class="card">
                <h3>⚡ 性能压力测试</h3>
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-value" id="responseTime">0</div>
                        <div class="stat-label">响应时间(ms)</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="memoryUsage">0</div>
                        <div class="stat-label">内存使用(MB)</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="queueLength">0</div>
                        <div class="stat-label">队列长度</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="errorRate">0</div>
                        <div class="stat-label">错误率(%)</div>
                    </div>
                </div>
                <div style="margin-top: 16px;">
                    <button class="button" onclick="startStressTest()">启动压力测试</button>
                    <button class="button danger" onclick="stopStressTest()">停止测试</button>
                    <button class="button warning" onclick="simulateHighLoad()">模拟高负载</button>
                </div>
            </div>
        </div>

        <!-- 实时日志 -->
        <div class="card">
            <h3>📋 实时系统日志</h3>
            <div class="log-container" id="logContainer">
                <!-- 日志条目将动态添加到这里 -->
            </div>
            <div style="margin-top: 16px;">
                <button class="button" onclick="clearLogs()">清除日志</button>
                <button class="button" onclick="exportLogs()">导出日志</button>
                <label style="color: #94a3b8; margin-left: 16px;">
                    <input type="checkbox" id="autoScroll" checked> 自动滚动
                </label>
            </div>
        </div>
    </div>

    <!-- 通知演示区域 -->
    <div class="notification-demo" id="notificationDemo">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
            <strong style="color: #00f5ff;">智能推送通知</strong>
            <span style="color: #94a3b8; font-size: 0.875rem;" id="notificationTime"></span>
        </div>
        <div id="notificationContent">这是一个测试通知内容</div>
        <div style="margin-top: 8px;">
            <span style="background: #10b981; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem;" id="notificationPriority">高优先级</span>
        </div>
    </div>

    <script>
        // 模拟智能Agent类
        class MockIntelligentAgent {
            constructor() {
                this.isActive = false;
                this.statistics = {
                    totalPushes: 0,
                    highPriorityPushes: 0,
                    announcements: 0,
                    policyMatches: 0,
                    userEngagement: 0
                };
                this.eventListeners = new Map();
                this.pushQueue = [];
                this.performanceMetrics = {
                    responseTime: 0,
                    memoryUsage: 0,
                    queueLength: 0,
                    errorRate: 0
                };
            }

            async initialize() {
                this.isActive = true;
                this.log('智能Agent代理启动中...', 'info');
                
                // 模拟初始化过程
                await this.delay(1000);
                
                this.log('✅ 智能Agent代理已启动', 'success');
                this.updateSystemStatus('online');
                
                // 启动定时任务
                this.startPeriodicTasks();
                
                return true;
            }

            stop() {
                this.isActive = false;
                this.log('🛑 智能Agent代理已停止', 'warning');
                this.updateSystemStatus('offline');
            }

            async generateCustomizedRecommendations() {
                const startTime = Date.now();
                
                this.log('🎯 开始生成定制化政策推荐...', 'info');
                
                // 模拟API调用延迟
                await this.delay(500 + Math.random() * 1000);
                
                const recommendations = [
                    {
                        id: 'policy_' + Date.now(),
                        title: '跨境电商税收优惠政策',
                        type: 'tax_policy',
                        urgency: 'high',
                        matchScore: 0.92,
                        benefit: '税负减免20-35%',
                        description: '针对跨境电商企业的综合税收优惠政策'
                    },
                    {
                        id: 'policy_' + (Date.now() + 1),
                        title: '制造业数字化转型补贴',
                        type: 'subsidy_policy',
                        urgency: 'medium',
                        matchScore: 0.85,
                        benefit: '最高补贴500万元',
                        description: '支持制造业企业进行数字化转型升级'
                    },
                    {
                        id: 'policy_' + (Date.now() + 2),
                        title: '新能源企业投资减免',
                        type: 'investment_policy',
                        urgency: 'low',
                        matchScore: 0.78,
                        benefit: '投资额15%税收抵免',
                        description: '促进新能源产业发展的投资优惠政策'
                    }
                ];

                this.statistics.policyMatches += recommendations.length;
                this.performanceMetrics.responseTime = Date.now() - startTime;
                
                this.log(`✅ 生成${recommendations.length}项政策推荐完成`, 'success');
                
                return recommendations;
            }

            queueHighPriorityPush(pushData) {
                const push = {
                    id: 'push_' + Date.now(),
                    ...pushData,
                    timestamp: Date.now(),
                    priority: 'high'
                };
                
                this.pushQueue.push(push);
                this.statistics.totalPushes += 1;
                this.statistics.highPriorityPushes += 1;
                
                this.log(`📤 高优先级推送: ${push.title}`, 'warning');
                
                // 触发通知显示
                this.showNotificationDemo(push);
                
                return push;
            }

            triggerDigitalHumanAnnouncement(announcement) {
                this.statistics.announcements += 1;
                this.log(`🎙️ 数字人播报: ${announcement.message}`, 'info');
                
                // 触发数字人播报动画
                this.startBroadcastAnimation(announcement);
                
                return announcement;
            }

            addEventListener(event, callback) {
                if (!this.eventListeners.has(event)) {
                    this.eventListeners.set(event, []);
                }
                this.eventListeners.get(event).push(callback);
            }

            emitEvent(event, data) {
                if (this.eventListeners.has(event)) {
                    this.eventListeners.get(event).forEach(callback => {
                        try {
                            callback(data);
                        } catch (error) {
                            this.log(`❌ 事件处理错误: ${error.message}`, 'error');
                        }
                    });
                }
            }

            getStatistics() {
                return {
                    ...this.statistics,
                    isActive: this.isActive,
                    queueLength: this.pushQueue.length,
                    ...this.performanceMetrics
                };
            }

            startPeriodicTasks() {
                if (!this.isActive) return;
                
                // 定期更新性能指标
                setInterval(() => {
                    if (this.isActive) {
                        this.updatePerformanceMetrics();
                    }
                }, 2000);
                
                // 模拟定期政策检查
                setInterval(() => {
                    if (this.isActive && Math.random() > 0.7) {
                        this.simulatePolicyUpdate();
                    }
                }, 10000);
            }

            updatePerformanceMetrics() {
                this.performanceMetrics.responseTime = 100 + Math.random() * 200;
                this.performanceMetrics.memoryUsage = 50 + Math.random() * 30;
                this.performanceMetrics.queueLength = this.pushQueue.length;
                this.performanceMetrics.errorRate = Math.random() * 2;
                
                this.updateStatsDisplay();
            }

            simulatePolicyUpdate() {
                const updates = [
                    '检测到新的跨境电商政策更新',
                    '制造业补贴政策条件调整',
                    '税收减免政策时间延长',
                    '新增企业数字化转型支持政策'
                ];
                
                const update = updates[Math.floor(Math.random() * updates.length)];
                
                this.queueHighPriorityPush({
                    title: '政策更新提醒',
                    content: update,
                    type: 'policy_update',
                    urgency: 'medium'
                });
            }

            showNotificationDemo(push) {
                const demo = document.getElementById('notificationDemo');
                const content = document.getElementById('notificationContent');
                const time = document.getElementById('notificationTime');
                const priority = document.getElementById('notificationPriority');
                
                content.textContent = push.content || push.title;
                time.textContent = this.formatTime(push.timestamp);
                priority.textContent = this.getUrgencyText(push.urgency);
                priority.style.background = this.getUrgencyColor(push.urgency);
                
                demo.classList.add('show');
                
                // 5秒后自动隐藏
                setTimeout(() => {
                    demo.classList.remove('show');
                }, 5000);
            }

            startBroadcastAnimation(announcement) {
                const avatar = document.getElementById('digitalAvatar');
                const message = document.getElementById('broadcastMessage');
                const progress = document.getElementById('broadcastProgress');
                
                avatar.classList.add('speaking');
                
                // 打字机效果
                this.typewriterEffect(message, announcement.message, () => {
                    // 播报进度动画
                    this.animateProgress(progress, announcement.duration || 5000, () => {
                        avatar.classList.remove('speaking');
                        message.textContent = '播报完成，等待下一条消息...';
                        progress.style.width = '0%';
                    });
                });
            }

            typewriterEffect(element, text, callback) {
                element.textContent = '';
                let index = 0;
                const speed = 50;
                
                const timer = setInterval(() => {
                    if (index < text.length) {
                        element.textContent += text[index];
                        index++;
                    } else {
                        clearInterval(timer);
                        if (callback) callback();
                    }
                }, speed);
            }

            animateProgress(element, duration, callback) {
                const startTime = Date.now();
                
                const timer = setInterval(() => {
                    const elapsed = Date.now() - startTime;
                    const progress = Math.min((elapsed / duration) * 100, 100);
                    
                    element.style.width = progress + '%';
                    
                    if (progress >= 100) {
                        clearInterval(timer);
                        if (callback) callback();
                    }
                }, 50);
            }

            updateStatsDisplay() {
                const stats = this.getStatistics();
                
                document.getElementById('totalPushes').textContent = stats.totalPushes;
                document.getElementById('highPriorityPushes').textContent = stats.highPriorityPushes;
                document.getElementById('announcements').textContent = stats.announcements;
                document.getElementById('policyMatches').textContent = stats.policyMatches;
                document.getElementById('responseTime').textContent = Math.round(stats.responseTime);
                document.getElementById('memoryUsage').textContent = Math.round(stats.memoryUsage);
                document.getElementById('queueLength').textContent = stats.queueLength;
                document.getElementById('errorRate').textContent = stats.errorRate.toFixed(1);
            }

            updateSystemStatus(status) {
                const indicator = document.getElementById('systemStatus');
                indicator.className = 'status-indicator status-' + status;
            }

            getUrgencyText(urgency) {
                const map = {
                    'high': '紧急',
                    'medium': '重要',
                    'low': '一般',
                    'normal': '普通'
                };
                return map[urgency] || '普通';
            }

            getUrgencyColor(urgency) {
                const map = {
                    'high': '#ef4444',
                    'medium': '#f59e0b',
                    'low': '#10b981',
                    'normal': '#0ea5e9'
                };
                return map[urgency] || '#0ea5e9';
            }

            formatTime(timestamp) {
                return new Date(timestamp).toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            }

            log(message, type = 'info') {
                const logContainer = document.getElementById('logContainer');
                const entry = document.createElement('div');
                entry.className = 'log-entry';
                
                const timestamp = this.formatTime(Date.now());
                entry.innerHTML = `
                    <span class="log-timestamp">[${timestamp}]</span>
                    <span class="log-${type}">${message}</span>
                `;
                
                logContainer.appendChild(entry);
                
                // 限制日志条目数量
                while (logContainer.children.length > 100) {
                    logContainer.removeChild(logContainer.firstChild);
                }
                
                // 自动滚动到底部
                if (document.getElementById('autoScroll').checked) {
                    logContainer.scrollTop = logContainer.scrollHeight;
                }
            }

            delay(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }
        }

        // 全局智能代理实例
        const intelligentAgent = new MockIntelligentAgent();

        // 测试函数
        async function startAgent() {
            try {
                await intelligentAgent.initialize();
                updateTestStatus('test-init', 'pass');
            } catch (error) {
                updateTestStatus('test-init', 'fail');
                intelligentAgent.log(`启动失败: ${error.message}`, 'error');
            }
        }

        function stopAgent() {
            intelligentAgent.stop();
        }

        function resetStats() {
            intelligentAgent.statistics = {
                totalPushes: 0,
                highPriorityPushes: 0,
                announcements: 0,
                policyMatches: 0,
                userEngagement: 0
            };
            intelligentAgent.updateStatsDisplay();
            intelligentAgent.log('📊 统计数据已重置', 'info');
        }

        async function testPolicyRecommendations() {
            try {
                const recommendations = await intelligentAgent.generateCustomizedRecommendations();
                updateTestStatus('test-recommendations', 'pass');
                intelligentAgent.log(`✅ 政策推荐测试通过，生成${recommendations.length}项推荐`, 'success');
            } catch (error) {
                updateTestStatus('test-recommendations', 'fail');
                intelligentAgent.log(`❌ 政策推荐测试失败: ${error.message}`, 'error');
            }
        }

        function testNotificationPush() {
            try {
                const testPush = {
                    title: '测试通知',
                    content: '这是一个测试推送通知，用于验证推送系统功能',
                    urgency: 'high',
                    type: 'test'
                };
                
                intelligentAgent.queueHighPriorityPush(testPush);
                updateTestStatus('test-notifications', 'pass');
                intelligentAgent.log('✅ 通知推送测试通过', 'success');
            } catch (error) {
                updateTestStatus('test-notifications', 'fail');
                intelligentAgent.log(`❌ 通知推送测试失败: ${error.message}`, 'error');
            }
        }

        function triggerManualBroadcast() {
            const announcement = {
                message: '这是一条手动触发的播报测试消息，用于验证数字人播报功能是否正常工作。',
                type: 'manual',
                urgency: 'normal',
                duration: 6000
            };
            
            intelligentAgent.triggerDigitalHumanAnnouncement(announcement);
            updateTestStatus('test-broadcast', 'pass');
        }

        function triggerUrgentBroadcast() {
            const announcement = {
                message: '紧急通知：检测到重要政策更新，请立即关注！这是一条高优先级播报消息。',
                type: 'urgent',
                urgency: 'high',
                duration: 8000
            };
            
            intelligentAgent.triggerDigitalHumanAnnouncement(announcement);
        }

        function triggerPolicyBroadcast() {
            const announcement = {
                message: '政策播报：新的跨境电商税收优惠政策已发布，预计可为符合条件的企业减免税负20-35%，建议及时关注申请条件。',
                type: 'policy',
                urgency: 'medium',
                duration: 10000
            };
            
            intelligentAgent.triggerDigitalHumanAnnouncement(announcement);
        }

        function stopBroadcast() {
            const avatar = document.getElementById('digitalAvatar');
            const message = document.getElementById('broadcastMessage');
            const progress = document.getElementById('broadcastProgress');
            
            avatar.classList.remove('speaking');
            message.textContent = '播报已停止';
            progress.style.width = '0%';
            
            intelligentAgent.log('⏹️ 数字人播报已停止', 'warning');
        }

        async function runAllTests() {
            intelligentAgent.log('🧪 开始运行全部测试...', 'info');
            
            // 重置测试状态
            const testIds = ['test-init', 'test-recommendations', 'test-notifications', 'test-broadcast', 'test-profile'];
            testIds.forEach(id => updateTestStatus(id, 'pending'));
            
            try {
                // 测试初始化
                await startAgent();
                
                // 测试政策推荐
                await testPolicyRecommendations();
                
                // 测试通知推送
                testNotificationPush();
                
                // 测试数字人播报
                triggerManualBroadcast();
                
                // 测试用户画像（模拟）
                updateTestStatus('test-profile', 'pass');
                intelligentAgent.log('✅ 用户画像分析测试通过', 'success');
                
                intelligentAgent.log('🎉 全部测试完成', 'success');
                
            } catch (error) {
                intelligentAgent.log(`❌ 测试过程中出现错误: ${error.message}`, 'error');
            }
        }

        let stressTestInterval;
        function startStressTest() {
            intelligentAgent.log('⚡ 启动性能压力测试...', 'warning');
            
            stressTestInterval = setInterval(() => {
                // 模拟高频推送
                for (let i = 0; i < 5; i++) {
                    intelligentAgent.queueHighPriorityPush({
                        title: `压力测试推送 #${Date.now()}`,
                        content: '这是压力测试生成的推送消息',
                        urgency: ['high', 'medium', 'low'][Math.floor(Math.random() * 3)],
                        type: 'stress_test'
                    });
                }
            }, 1000);
        }

        function stopStressTest() {
            if (stressTestInterval) {
                clearInterval(stressTestInterval);
                stressTestInterval = null;
                intelligentAgent.log('⏹️ 压力测试已停止', 'info');
            }
        }

        function simulateHighLoad() {
            intelligentAgent.log('🔥 模拟高负载场景...', 'warning');
            
            // 快速生成大量推送
            for (let i = 0; i < 20; i++) {
                setTimeout(() => {
                    intelligentAgent.queueHighPriorityPush({
                        title: `高负载测试 #${i + 1}`,
                        content: `这是第${i + 1}条高负载测试消息`,
                        urgency: 'high',
                        type: 'load_test'
                    });
                }, i * 100);
            }
        }

        function updateTestStatus(testId, status) {
            const element = document.getElementById(testId);
            element.className = `test-status test-${status}`;
            element.textContent = status === 'pass' ? '通过' : status === 'fail' ? '失败' : '待测试';
        }

        function clearLogs() {
            document.getElementById('logContainer').innerHTML = '';
        }

        function exportLogs() {
            const logs = Array.from(document.getElementById('logContainer').children)
                .map(entry => entry.textContent)
                .join('\n');
            
            const blob = new Blob([logs], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `agent-logs-${new Date().getTime()}.txt`;
            a.click();
            URL.revokeObjectURL(url);
            
            intelligentAgent.log('📁 日志已导出', 'info');
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            intelligentAgent.log('🌐 智能Agent测试页面已加载', 'success');
            intelligentAgent.updateStatsDisplay();
            
            // 显示欢迎消息
            setTimeout(() => {
                const welcomeMessage = {
                    message: '欢迎使用智能Agent代理系统测试平台！请点击"启动代理"开始测试。',
                    type: 'welcome',
                    urgency: 'normal',
                    duration: 5000
                };
                intelligentAgent.startBroadcastAnimation(welcomeMessage);
            }, 1000);
        });
    </script>
</body>
</html> 